﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.IO;
using System.Windows.Resources;
using System.IO.IsolatedStorage;
using System.Net.Browser;
using System.Windows.Navigation;

namespace WhereAmI
{

    // Nokia Maps API
    // api.maps.nokia.com/

    // Bing Maps API
    // http://www.microsoft.com/maps/
    // http://msdn.microsoft.com/en-us/library/gg427610.aspx


    public partial class MainPage : PhoneApplicationPage
    {
        private BrowserMouseHelper moveHelper;
        
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            webBrowser.Opacity = 0;

            // Enable Geolocation and javascript for the browser
            webBrowser.IsGeolocationEnabled = true;
            webBrowser.IsScriptEnabled = true;

            moveHelper = new BrowserMouseHelper(ref webBrowser);
            moveHelper.ScrollDisabled = true;


            // Store all HTML, Javascript, CSS and image files into isolated storage and use them for there
            SaveFilesToIsoStore();

            // Listening javascript notifications from HTML
            webBrowser.ScriptNotify += new EventHandler<NotifyEventArgs>(webBrowser_ScriptNotify);
        }

        /// <summary>
        /// Open index.html page when this Silverlight page is opened
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            webBrowser.Navigate(new Uri("html_content/index.html", UriKind.Relative));
        }

        /// <summary>
        /// Close info html page if user press device Back key there
        /// </summary>
        /// <param name="e"></param>
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);

            if (isInfoVisible())
            {
                e.Cancel = true;
                CloseInfo();
            }
            else
            {
                e.Cancel = false;
            }
        }

        /// <summary>
        /// Javascript calls C#. Show message to the user as MessageBox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void webBrowser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            MessageBox.Show(e.Value);
        }

        /// <summary>
        /// Html page loaded, show webbrowser
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            logo.Opacity = 0;
            // Show browser
            webBrowser.Opacity = 1;
        }

        /// <summary>
        /// Store all HTML, Javascript, CSS and image files into isolated storage and use them for there
        /// </summary>
        private void SaveFilesToIsoStore()
        {
            //These files must match what is included in the application package,
            //or BinaryStream.Dispose below will throw an exception.
            
            string[] files = {
            "html_content/index.html",
            "html_content/css/whereami.css",
            "html_content/images/marker.png",
            "html_content/js/geolocation.js",
            "html_content/js/staticmap.js"
            };

            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            // For testing
            isoStore.Remove();

            foreach (string f in files)
            {
                StreamResourceInfo sr = Application.GetResourceStream(new Uri(f, UriKind.Relative));
                using (BinaryReader br = new BinaryReader(sr.Stream))
                {
                    byte[] data = br.ReadBytes((int)sr.Stream.Length);
                    SaveToIsoStore(f, data);
                }
            }
        }

        private void SaveToIsoStore(string fileName, byte[] data)
        {
            string strBaseDir = string.Empty;
            string delimStr = "/";
            char[] delimiter = delimStr.ToCharArray();
            string[] dirsPath = fileName.Split(delimiter);

            //Get the IsoStore.
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            //Re-create the directory structure.
            for (int i = 0; i < dirsPath.Length - 1; i++)
            {
                strBaseDir = System.IO.Path.Combine(strBaseDir, dirsPath[i]);
                isoStore.CreateDirectory(strBaseDir);

            }

            //Remove the existing file.
            if (isoStore.FileExists(fileName))
            {
                isoStore.DeleteFile(fileName);
            }

            //Write the file.
            using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fileName)))
            {
                bw.Write(data);
                bw.Close();
            }
        }

        /// <summary>
        /// Call javascript to update map
        /// </summary>
        private void UpdateMap()
        {
            try
            {
                if (isInfoVisible() == false)
                    webBrowser.InvokeScript("update");
            }
            catch { }

        }

        /// <summary>
        /// Ask from javascript is info page visible
        /// </summary>
        /// <returns></returns>
        private bool isInfoVisible()
        {
            try
            {
                int ret = Int32.Parse((string)(webBrowser.InvokeScript("isInfoVisible")));
                if (ret == 0)
                    return false;
                else
                    return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Ask javascript to open info page
        /// </summary>
        private void ShowInfo()
        {
            try
            {

                webBrowser.InvokeScript("showInfo");
            }
            catch { }
        }

        /// <summary>
        /// Ask javascript to close info
        /// </summary>
        private void CloseInfo()
        {
            try
            {
                webBrowser.InvokeScript("closeInfo");
            }
            catch { }
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            ShowInfo();
        }

        private void ApplicationBarMenuItem_Click_1(object sender, EventArgs e)
        {
            UpdateMap();
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            UpdateMap();
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            ShowInfo();
        }


    }
}